<?php
class TasksController extends AppController {

	var $name = 'Tasks';
	
	var $uses = array('Task', 'Project', 'Time', 'Media', 'Comment', 'User');
	var $helpers = array('Html', 'Session', 'Date', 'Form');
	
	function beforeFilter() {
		parent::beforeFilter();
		
		if ( preg_match('/\b(add)|(update)\b/', $this->params['action']) && $this->Auth->user('role') == 'spectator')
		{
			$this->redirect('/');
		}
	}

	function index($prj_id = null, $back_url = null) {
		
		if ($prj_id)
		{
			if ($this->check_permissions_for_project($this->Auth->user(), $prj_id))
			{
				$this->set_profile_parametr('selected_project', $prj_id);
				$this->redirect((!empty($back_url)) ? base64_decode($back_url) : '/tasks/index');
			}
			$this->redirect('/');
		}
		
		$this->Task->recursive = 0;
		
		$times_ =  $this->Time->find('all', array('conditions' => array('Time.status !=' => 'stop', 'user_id' => $this->Auth->user('id'))));
		
		$times = array();
		foreach($times_ as $time) {
			$times[$time['Time']['task_id']] = $time;
		}
		
		$order = $this->get_order_for_tasks();
		
		if (!empty($this->data['Filter'])) {
			if (!empty($this->data['Filter']['status']))
			{
				switch($this->data['Filter']['status']) {
					case 'open':
					case 'close':
					{
						$this->set_profile_parametr('selected_status', $this->data['Filter']['status']);
						break;
					}
					case 'all':
					default:
					{
						$this->set_profile_parametr('selected_status', 'all');
						break;
					}
				}
			}
			
			if (!empty($this->data['Filter']['user']))
			{
				switch($this->data['Filter']['user']) {
					case 'my':
					{
						$this->set_profile_parametr('selected_user', 'my');
						break;
					}
					case 'all':
					{
						$this->set_profile_parametr('selected_user', 'all');
						break;
					}
					default:
					{
						if (is_numeric($this->data['Filter']['user']))
						{
							$this->set_profile_parametr('selected_user', $this->data['Filter']['user']);
						}
						else
						{
							$this->set_profile_parametr('selected_user', 'all');
						}
						break;
					}
				}
			}
		}
		
		$conditions = array(
			'project_id' => $this->current_project['Project']['id']
		);
		
		if ($this->get_profile_parametr('selected_status') == 'open')
		{
			$conditions['Task.status !='] = 'closed';
		}
		elseif ($this->get_profile_parametr('selected_status') == 'close') {
			$conditions['Task.status'] = 'closed';
		}
		
		if ($this->get_profile_parametr('selected_user') == 'my')
		{
			$conditions['Task.performer_id'] = $this->Auth->user('id');
		}
		elseif (is_numeric($this->get_profile_parametr('selected_user'))) {
			$conditions['Task.performer_id'] = $this->get_profile_parametr('selected_user');
		}
		
		$tasks = $this->Task->find('all', array(
			'conditions' => $conditions,
			'order' => array($order)
		));
		
		$users_in_project = $this->Project->get_project_users($this->current_project['Project']['id']);
		unset($users_in_project[$this->Auth->user('id')]);
		if ($this->Auth->user('role') != 'spectator') {
			$users_in_project['my'] = 'my';
		}
		$users_in_project['all'] = 'all';
		
		$this->set('tasks', $tasks);
		$this->set('times', $times);
		$this->set('users_in_project', $users_in_project);
		$this->set('selected_user', $this->get_profile_parametr('selected_user'));
		$this->set('selected_status', $this->get_profile_parametr('selected_status'));
		$this->set('current_project', $this->Project->read(null, $this->current_project['Project']['id']));
	}

	function view($task_id = null) {
		
		$current_user = $this->Auth->user();
		
		if (!$this->check_permissions_for_task($current_user, $task_id))
		{
			$this->redirect('/');
		}
		
		if (!$task_id) {
			$this->Session->setFlash(__('Invalid task', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Task->recursive = 2;
		$task = $this->Task->read(null, $task_id);
		$this->Task->recursive = 0;
		$users = $this->Project->get_project_users($this->current_project['Project']['id']);
		
		unset($users[$task['Task']['performer_id']]);
		
		$times = $this->Time->find('all', array('conditions' => array(
			'Time.task_id' => $task_id,
			'Time.status' => 'stop'
		)));
				
		//debug($times);
		
		$this->Task->recursive = 2;
		$this->set('task', $task);
		$this->set('users', $users);
		$this->set('times', $times);
	}

	function add() {
		
		$current_user = $this->Auth->user();
		
		if (!$this->check_permissions_for_project($current_user, $this->current_project['Project']['id']))
		{
			$this->redirect('/');
		}
		
		if (!empty($this->data)) {
			
			$this->data['Task']['creator_id'] = $this->Auth->user('id');
			$this->data['Task']['project_id'] = $this->current_project['Project']['id'];
			$this->data['Task']['status'] = 'opened';
			
			$this->data['Task']['name'] = preg_replace ( '/<.*?>/i' , '' , $this->data['Task']['name']);
			
			$this->data['Task']['desc'] = preg_replace ( '/ ?[\w:\-]+ ?= ?("[^"]+"|\'[^\']+\'|\w+)/i' , '' , $this->data['Task']['desc']);
			$this->data['Task']['desc'] = preg_replace ( '/(<script.*?script>)|(<style.*?style>)/i' , '' , $this->data['Task']['desc']);
			
			$files = $this->data['Files'];
			unset($this->data['Files']);
			
			
			$this->Task->create();
			if ($this->Task->save($this->data)) {
				
				$media = array();
				srand(time());
				foreach($files as $file)
				{
					if ($file['error'] == 0)
					{
						$ext = explode('.', $file['name']);
						$ext = $ext[count($ext) - 1];
						$new_name = '';
						do{
							$new_name = $this->Task->id . '-' . md5($new_name.$file['name'].rand()) . '.' . $ext;
						}while(file_exists($new_name));
						$media[] = array('Media' => array(
							'parent_id' => $this->Task->id,
							'name' => $new_name,
							'parent_type' => 'task',
							'alias' => $file['name']
						));
						move_uploaded_file($file['tmp_name'], WWW_ROOT.'files'.DS.$new_name);
					}
				}
				
				$this->Media->SaveAll($media);
				$this->redirect(array('action' => 'index'));
			}
		}
		
		$this->set('performers', $this->Project->get_project_users($this->current_project['Project']['id']));
	}

	function update() {
		
		if (empty($this->data)) {
			$this->redirect('/');
		}
		
		$current_user = $this->Auth->user();
		
		if (!$this->check_permissions_for_task($current_user, $this->data['Task']['id']))
		{
			$this->redirect('/');
		}
		
		if (!empty($this->data)) {
			
			$task = $this->Task->find('first', array('conditions' => array('Task.id' => $this->data['Task']['id'])));
			
			if (empty($task))
			{
				$this->redirect('/');
			}
			
			if (!empty($this->data['Task']['status']))
			switch($this->data['Task']['status'])
			{
				case 'closed' : {
					
					if ($task['Task']['status'] == 'closed')
					{
						$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
					}
					else
					{
						$this->data['Task']['comment'] = preg_replace ( '/ ?[\w:\-]+ ?= ?("[^"]+"|\'[^\']+\'|\w+)/i' , '' , $this->data['Task']['comment']);
						$this->data['Task']['comment'] = preg_replace ( '/(<script.*?script>)|(<style.*?style>)/i' , '' , $this->data['Task']['comment']);
						
						$this->Task->save(array('Task' => array('id' => $task['Task']['id'], 'status' => 'closed')), array('fieldList' => array('id', 'status')));
						$this->Comment->save(array('Comment' => array(
							'task_id' => $task['Task']['id'],
							'user_id' => $this->Auth->user('id'),
							'text' => '<div>'.$this->Auth->user('username').' change status from <i>'.$task['Task']['status'].'</i> to <i>'.$this->data['Task']['status'].'</i></div>'.$this->data['Task']['comment']
						)));
					}
					
					$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
					break;
				}
				
				case 'reopened' : {
					
					if ($task['Task']['status'] != 'closed')
					{
						$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
					}
					else
					{
						$this->data['Task']['comment'] = preg_replace ( '/ ?[\w:\-]+ ?= ?("[^"]+"|\'[^\']+\'|\w+)/i' , '' , $this->data['Task']['comment']);
						$this->data['Task']['comment'] = preg_replace ( '/(<script.*?script>)|(<style.*?style>)/i' , '' , $this->data['Task']['comment']);
						
						$this->Task->save(array('Task' => array('id' => $task['Task']['id'], 'status' => 'reopened')), array('fieldList' => array('id', 'status')));
						$this->Comment->save(array('Comment' => array(
							'task_id' => $task['Task']['id'],
							'user_id' => $this->Auth->user('id'),
							'text' => '<div>'.$this->Auth->user('username').' change status from <i>'.$task['Task']['status'].'</i> to <i>'.$this->data['Task']['status'].'</i></div>'.$this->data['Task']['comment']
						)));
					}
					
					$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
					break;
				}
				
				case 'reassigned' : {
					
					$this->data['Task']['comment'] = preg_replace ( '/ ?[\w:\-]+ ?= ?("[^"]+"|\'[^\']+\'|\w+)/i' , '' , $this->data['Task']['comment']);
					$this->data['Task']['comment'] = preg_replace ( '/(<script.*?script>)|(<style.*?style>)/i' , '' , $this->data['Task']['comment']);
					
					$user = $this->User->find('first', array('conditions' => array('User.id' => $this->data['Task']['performer_id'])));
					
					if (empty($user))
					{
						$this->redirect('/');
					}
					
					$reopen = '';
					if ($task['Task']['status'] == 'closed')
					{
						$reopen = ' reopen task and';
					}

					$this->Task->save(
						array('Task' => array(
							'id' => $task['Task']['id'],
							'status' => 'reassigned',
							'performer_id' => $this->data['Task']['performer_id']
							)
						),
						array('fieldList' => array('id', 'status', 'performer_id'))
					);
					$this->Comment->save(array('Comment' => array(
						'task_id' => $task['Task']['id'],
						'user_id' => $this->Auth->user('id'),
						'text' => '<div><i>'.$this->Auth->user('username').'</i>'.$reopen.' reassign to <i>'.$user['User']['username'].'</i></div>'.$this->data['Task']['comment']
					)));
					
					$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
					break;
				}
			}
			
			if (!empty($this->data['Task']['priority']))
			{
				if ($task['Task']['priority'] != $this->data['Task']['priority'])
				{
					$priority = array(1 => 'low', 2 => 'medium', 3 => 'high');
					$this->Task->save(
						array('Task' => array(
							'id' => $task['Task']['id'],
							'priority' => $this->data['Task']['priority']
							)
						),
						array('fieldList' => array('id', 'priority'))
					);
					$this->Comment->save(array('Comment' => array(
						'task_id' => $task['Task']['id'],
						'user_id' => $this->Auth->user('id'),
						'text' => '<div><i>'.$this->Auth->user('username').'</i> change priority from ' . $priority[$task['Task']['priority']] . ' to ' . $priority[$this->data['Task']['priority']] . '</div>'
					)));
				}
			}
			
			$this->redirect(array('controller' => 'tasks', 'action' => 'view', $task['Task']['id']));
	
		}
		
		$this->redirect('/');
	}
}
